﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BookReader
{
    class opCommand:ICommand
    {
        #region ICommand 成员

        void ICommand.Execute(string[] param)
        {
            if (param == null || param.Length != 1)
            {
                Console.WriteLine("参数不正确，正确示例" + ((ICommand)this).Help());
                StaticData.openFilepath = string.Empty;
                return;
            }
            string Openpath = string.Empty;
            int id = 0;
            if (int.TryParse(param[0], out id))
            {
                DirectoryInfo dir = new DirectoryInfo(StaticData.workingDir);
                FileInfo[] fs = dir.GetFiles("*.txt");
                if (id < (fs.Length + 1) && id > 0)
                {
                    for (int i = 1; i < (fs.Length + 1); i++)
                    {
                        if (id == i)
                        {
                            Openpath = fs[i - 1].FullName;
                            StaticData.openFilepath = fs[i - 1].Name;
                            break;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("序号超出范围");
                    return;
                }
            }
            else
            {
                Openpath = StaticData.workingDir + "\\" + param[0];
                StaticData.openFilepath = param[0];
            }

            
            if (!File.Exists(Openpath))
            {
                Console.WriteLine("文件[" + Openpath + "]不存在");
                StaticData.openFilepath = string.Empty;
            }
            else
            {
                Service.OpenBook(Openpath, StaticData.lines);
                int Rem = 0;
                int PageCount = Math.DivRem(StaticData.lines.Count, StaticData.pageSize, out Rem);
                if (Rem > 0)
                    PageCount++;
                StaticData.PageCount = PageCount;
                StaticData.PageIndex = 0;
                int start = StaticData.PageIndex * StaticData.pageSize;
  
                for (int i = start, lc = 0; lc < StaticData.pageSize; i++, lc++)
                {
                    if (i < StaticData.lines.Count)
                    {
                        Console.WriteLine(StaticData.lines[i]);
                        StaticData.currentIndex = i;
                        StaticData.Reading = true;
                    }
                }
                if (StaticData.PageIndex == (PageCount - 1))
                {
                    Console.WriteLine("没有下文了");
                }
               
            }

        }

        string ICommand.Help()
        {
            return "op命令：打开文件，格式 op 文件名 或 op 序号 注：文件名不能包含逗号";
        }

        #endregion
    }
}
